<?php

/**
 * calendrier actions.
 *
 * @package    sop
 * @subpackage calendrier
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 2692 2006-11-15 21:03:55Z fabien $
 */
class calendrierActions extends sfActions {
  
  /*
   * traite les donnes post avant l'affichage
   * TODO: empecher les modifs par request si pas validCadre = true
   */

  public function executeSubmit(sfWebRequest $request) {
    sfContext::getInstance()->getConfiguration()->loadHelpers('Util');
    
    $salarie       = SalariePeer::retrieveByPK($request->getParameter('id'));
    $auth_salarie  = $this->getUser()->getGuardUser()->getSalaries();
    $auth_salarie  = array_pop($auth_salarie);

    foreach ($this->getRequest()->getParameterHolder()->getNames() as $idParamRequest) {
      //on trouve un type de journée pour un jour de la semaine précis
      if (preg_match('/posting_day_([0-9]+)/', $idParamRequest, $matches)) {
        //Recuperation du jour
        $jour = JourPeer::retrieveByPk($matches[1]);
        $log = new Log();

        //modif du type ?
        if ($request->hasParameter('type_jour_' . $jour->getId())) {
          $jour->setType($request->getParameter('type_jour_' . $jour->getId()));
          $log->setTypeId($jour->getType());
        }

        if ($request->hasParameter('uf') && $request->getParameter('uf') != null) {
          $uf = UniteFonctionnellePeer::retrieveByPk($request->getParameter('uf'));

          if (!$uf instanceof UniteFonctionnelle)
            throw new Exception("Aucune unité fonctionnelle ne correspond à l'identifiant indiqué: $uf !");
        }
        
        $type = TypeJourPeer::retrieveByPK($jour->getType());
        $jour->setIsDeplact($type->getIsDeplact());
        
        //horaires et pause si demande de modif et possibilit� de modif
        if (!$type->isOnlyDuree() && $this->getRequest()->hasParameter('heure_arrivee_' . $jour->getId())) {
          $paramHeureArrivee = $this->getRequestParameter('heure_arrivee_' . $jour->getId());
          $heures = rAddZero($paramHeureArrivee['hour']);
          $minutes = rAddZero($paramHeureArrivee['minute']);
          $objDateArrivee = new clDate($jour->getObjDate()->getDate("Y-m-d $heures:$minutes:00"));
          $jour->setHeureArrivee($objDateArrivee->getDateTime());
          $paramHeureDepart = $this->getRequestParameter('heure_depart_' . $jour->getId());
          $heures = rAddZero($paramHeureDepart['hour']);
          $minutes = rAddZero($paramHeureDepart['minute']);
          $objDateDepart = new clDate($jour->getObjDate()->getDate("Y-m-d $heures:$minutes:00"));
          $jour->setHeureDepart($objDateDepart->getDateTime());
          $jour->setDureePause($this->getRequestParameter('duree_pause_' . $jour->getId()));

          $log->setHeureDepart($objDateDepart->getDateTime());
          $log->setHeureArrivee($objDateArrivee->getDateTime());
          $log->setTempsPause($this->getRequestParameter('duree_pause_' . $jour->getId()));
          $log->calTotalJournee();
          //Sinon demande manuelle de la dur�e travaill�e du jour
        } else
        if ($type->isOnlyDuree() && !$type->isObligDuree() && $this->getRequest()->hasParameter('temps_travaille_' . $jour->getId())) {
          $jour->setTotalJournee(60 * $request->getParameter('temps_travaille_' . $jour->getId()));
          $log->setTotalJournee(60 * $request->getParameter('temps_travaille_' . $jour->getId()));
        }
        //Commentaire ?
        if ($this->getRequest()->hasParameter('commentaire_jour_' . $jour->getId())) {
          $jour->setCommentaire($this->getRequest()->getParameter('commentaire_jour_' . $jour->getId()));
        }
        // log si changement validation cadre
        if ($request->hasParameter('validation_' . $jour->getId()) && (!$jour->getIsValide() && !$jour->getIsValideResponsable())) {
          $log->setDtModif(time());
          $log->setGuardId($this->getUser()->getGuardUser()->getPrimaryKey());
          $log->setDate($jour->getDate());
          $log->setTotalJournee($jour->getTotalJournee());
          $log->setUserId($salarie->getsfGuardUser()->getPrimaryKey());

          $log->save();
        }

        $jour->setIsCredit($type->getIsCredit());
        
        $date_lundi     = DateTime::createFromFormat('d/m/Y', $request->getParameter('df_day') . "/" . $request->getParameter("df_month") . "/" . $request->getParameter("df_year"));
        $date_actuelle  = new DateTime('now');

        if(!$jour->getIsValideResponsable() && $date_lundi > $date_actuelle->sub(new DateInterval('P3M')))
          $jour->save();

        //validation du cadre ?
        if(isset($uf) && $auth_salarie->isResponsable($uf)) {
          if($request->hasParameter('validation_responsable_' . $jour->getPrimaryKey()))
            $jour->setIsValideResponsable(1);
          else
            $jour->setIsValideResponsable(0);
        } 
          if($request->hasParameter('validation_agent_' . $jour->getPrimaryKey()) && !$jour->getIsValideResponsable())
            $jour->setIsValide(1);
          elseif(!$jour->getIsValideResponsable())
            $jour->setIsValide(0);
        

        if($date_lundi > $date_actuelle->sub(new DateInterval('P3M')))
          $jour->save();
      }
      //si demande de modif pour un parametre de la semaine
      if (isset($jour) && is_object($jour)) {
        if ($request->hasParameter('commentaire_semaine')) {
          if (!$jour->getSemaine()) //fix donnes corrompues database
            $jour->setSemaine(SemainePeer::getSemaineTravail($jour->getSalarie(), clDate::getMondayFromWeekNumber($jour->getObjDate()->getYear(), $jour->getObjDate()->getWeekNumber())));
          $jour->getSemaine()->setCommentaire($request->getParameter('commentaire_semaine'));
          $jour->getSemaine()->save();
        }
      }
    }

    $jour = $jour->getObjDate()->getLastMonday();

    $uf_part = isset($uf) ? '&uf=' . $uf->getPrimaryKey() : '';
    $this->redirect('calendrier/index?id=' . $request->getParameter('id')
            . $uf_part
            . '&df_day=' . $jour->getDate('d')
            . '&df_month=' . $jour->getDate('m')
            . '&df_year=' . $jour->getDate('Y')
    );
  }

  /**
   * Affiche le calendrier
   *
   */
  public function executeIndex(sfWebRequest $request) {
    sfContext::getInstance()->getConfiguration()->loadHelpers('Util');

    /* bloc vérification permissions && url valide */
    $mod = false;
    $auth = true;

    if (!($request->getParameter('id') > 0))
      $auth = false;
    
    $this->salarie = SalariePeer::retrieveByPk($request->getParameter('id'));

    if ($request->hasParameter('uf') && $request->getParameter('uf') != null) {
      $uf = UniteFonctionnellePeer::retrieveByPk($request->getParameter('uf'));
      if (!$uf instanceof UniteFonctionnelle)
        throw new Exception("Aucune unité fonctionnelle ne correspond à l'identifiant indiqué: $uf !");
    }

    $salarie = SalariePeer::getSalariesByUserId($this->getUser()->getGuardUser()->getPrimaryKey());

    // parametres de l'affichage
    $tab = array();
    $this->tabChoixPause = array();
    for ($nbMin = 0; $nbMin <= 120; $nbMin = $nbMin + 5) {
      $a = min2rep($nbMin);
      $tab[$nbMin] = $a;
    }

    $tab[180] = min2rep(180);
    $this->tabChoixPause = $tab;
    $this->tabChoixDuree = array();
    $tab = array();
    for ($i = 0; $i <= 14; $i++) {
      $tab[$i * 60] = $i . 'h';
    }
    $this->tabChoixDuree = $tab;

    //chargement du salarie && semaine
    if ($request->hasParameter('df_day')) {
      $dateDemandee = new clDate(
              rAddZero($request->getParameter('df_day')) . "/" .
              rAddZero($request->getParameter("df_month")) . "/" .
              $request->getParameter("df_year")
      );
      
      $string_date   = rAddZero($request->getParameter('df_day')) . "/" . rAddZero($request->getParameter("df_month")) . "/" . $request->getParameter("df_year");
      $date_demande  = DateTime::createFromFormat('d/m/Y', $string_date);
      $date_actuelle = new DateTime();

      if($date_demande < $date_actuelle->sub(new DateInterval('P3M')))
        $this->readonly = true;
      else
        $this->readonly = false;

      $this->currentYear = $dateDemandee->getYear();
      $this->idSemaine = $dateDemandee->getWeekNumber();
    } else {
      $today = clDate::makeDateToday();
      $this->idSemaine = $today->getWeekNumber();
      $this->currentYear = $today->getYear();
      $dateDemandee = $today;
    }

    $currentLundi = $dateDemandee->getLastMonday();
    $this->semaine = SemainePeer::getSemaineTravail($this->salarie, $currentLundi);
    $this->strMondayCurrentWeek = $currentLundi->getDate('m/d/Y');

    $this->validUrl = 'calendrier/submit?id=' . $this->salarie->getId()
            . '&df_day=' . $currentLundi->getDate('d')
            . '&df_month=' . $currentLundi->getDate('m')
            . '&df_year=' . $currentLundi->getDate('Y');

    $dateTemp = clone $currentLundi;
    $this->tabJours = getListeJours();
    $this->tabJoursCurrentSemaine = array();
    $tab = array();
    for ($i = 0; $i < 7; $i++) {
      $jourTravail = JourPeer::getJourTravail($this->salarie, $dateTemp);
      $tab[$i] = $jourTravail;
      $dateTemp->addDays(1);
    }
    $this->tabJoursCurrentSemaine = $tab;

    if (isset($uf))
      $this->uf = $uf->getPrimaryKey();
  }

  public function executeView(sfWebRequest $request) {
    sfContext::getInstance()->getConfiguration()->loadHelpers('Util');
    
    $this->salarie = SalariePeer::retrieveByPk($request->getParameter('id'));

    $this->mod = false;

    //parametres
    $tabChoixPause = array();
    for ($nbMin = 0; $nbMin <= 120; $nbMin = $nbMin + 10) {
      $tabChoixPause[$nbMin] = min2rep($nbMin);
    }
    $tabChoixPause[180] = min2rep(180);
    $this->tabChoixPause = $tabChoixPause;
    
    $tabChoixDuree = array();
    for ($i = 0; $i <= 14; $i++) {
      $tabChoixDuree[$i * 60] = $i . 'h';
    }
    $this->tabChoixDuree = $tabChoixDuree;

    //chargement du salari�
    //chargement du de la semaine en cours
    if ($request->hasParameter('df_day')) {
      $dateDemandee = new clDate(
              rAddZero($request->getParameter('df_day')) . "/" .
              rAddZero($request->getParameter("df_month")) . "/" .
              $request->getParameter("df_year")
      );
      $this->currentYear = $dateDemandee->getYear();
      $this->idSemaine = $dateDemandee->getWeekNumber();
    } else {
      $today = clDate::makeDateToday();
      $this->idSemaine = $today->getWeekNumber();
      $this->currentYear = $today->getYear();
    }

    $currentLundi = clDate::getMondayFromWeekNumber($this->currentYear, $this->idSemaine);

    $this->semaine = SemainePeer::getSemaineTravail($this->salarie, $currentLundi);
    $this->strMondayCurrentWeek = $currentLundi->getDate('m/d/Y');

    $this->validUrl = 'calendrier/submit?id=' . $this->salarie->getId()
            . '&df_day=' . $currentLundi->getDate('d')
            . '&df_month=' . $currentLundi->getDate('m')
            . '&df_year=' . $currentLundi->getDate('Y');
    
    $dateTemp = clone $currentLundi;
    $this->tabJours = getListeJours();
    
    $tabJoursCurrentSemaine = array();
    for ($i = 0; $i < 7; $i++) {
      $jourTravail = JourPeer::getJourTravail($this->salarie, $dateTemp);
      $tabJoursCurrentSemaine[$i] = $jourTravail;
      $dateTemp->addDays(1);
    }
    $this->tabJoursCurrentSemaine = $tabJoursCurrentSemaine;
  }

}
